using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace AcqEncoder.TcpIp
{
	public class RemoteTcpClientUnpack : RemoteTcpClient
	{
		private bool _runFlag = true;

		public int PackageLen { get; set; }

		public Action<int, byte[]> RcvPackageCompletedHandler { get; set; }

		public Action<Exception> RcvErrorHandler { get; set; }

		public RemoteTcpClientUnpack(TcpClient client)
			: base(client)
		{
		}

		public override void Dispose()
		{
			this._runFlag = false;
			base.Dispose();
		}

		public override void RcvData()
		{
			int num = 0;
			List<byte> list = new List<byte>();
			byte[] array = new byte[this.PackageLen];
			StringBuilder stringBuilder = new StringBuilder();
			while (this._runFlag)
			{
				num = base.Client.Available;
				try
				{
					if (num > 0)
					{
						base.RcvByteBuf = new byte[num];
						base.Client.Client.Receive(base.RcvByteBuf);
						list.AddRange(base.RcvByteBuf);
						base.SumTime = 0;
					}
					else
					{
						base.SumTime += base.ReadInterval;
					}
					if (this.PackageLen > 0)
					{
						if (list.Count >= this.PackageLen)
						{
							int num2 = list.Count / this.PackageLen;
							int num3 = 0;
							while (num2 > 0 && this._runFlag)
							{
								for (int i = 0; i < this.PackageLen; i++)
								{
									array[i] = list[i];
								}
								list.RemoveRange(0, this.PackageLen);
								this.RcvPackageCompletedHandler?.Invoke(num3, array);
								num2 = list.Count / this.PackageLen;
								num3++;
							}
						}
					}
					else
					{
						this.RcvPackageCompletedHandler?.Invoke(0, base.RcvByteBuf);
					}
					if (base.SumTime >= base.TimeReadOut)
					{
						base.ReadOutHandler?.Invoke(base.UserIp, base.UserPort);
						return;
					}
				}
				catch (Exception obj)
				{
					this.RcvErrorHandler?.Invoke(obj);
				}
				Thread.Sleep(base.ReadInterval);
			}
		}
	}
}
